import os
import urllib.request
import logging
import sys
from urllib.parse import urlparse
logging.basicConfig(
    format='%(asctime)s %(levelname)s %(message)s',
    level=logging.INFO,
    stream=sys.stdout
)

def download(save_dir, file_name, url):
    """下载文件到指定目录，并使用指定的文件名保存"""
    save_path = os.path.join(save_dir, file_name)
    try:
        urllib.request.urlretrieve(url, save_path)
    except Exception as e:
        logging.error(f"文件下载Error when retrieving the URL: {e}")

def down(url):
    try:
        # 替换为您需要的URL和文件名
        # url = 'http://sm.valuemap.cn/file/group2/M00/06/C6/wKgBo2asptqAQd--AAGQ1_ZS-lE668.pdf?filename=202408021728586268460.pdf'
        # 解析 URL 获取文件名
        parsed_url = urlparse(url)
        file_name = parsed_url.query.split('=')[1]# 确保文件名与URL中的文件名一致或您想要的名称

        # 获取文件目录
        save_dir = 'D:/liushuipdf'
        if not os.path.exists(save_dir):
            logging.info(f"Creating directory '{save_dir}'.")
            os.makedirs(save_dir)

        full_path = os.path.join(save_dir, file_name)
        if not os.path.isfile(full_path):
            logging.info("File doesn't exist. Downloading now.")
            download(save_dir, file_name, url)
        else:
            logging.info(f"File '{file_name}' already exists in directory: {save_dir}")
        return save_dir+'/'+file_name
    except Exception as e:
        logging.error(f"Error when downloading the file: {e}")
        return ""


